package cn.zdxiang.base.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

/**
 * Base activity
 * @date 2020/5/9
 * @author Jm
 */
abstract class BaseVmActivity : AppCompatActivity() {

    private var mActivityProvider: ViewModelProvider? = null

    private var dataBindingConfig: DataBindingConfig? = null

    private var mBinding: ViewDataBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModel()
        dataBindingConfig = getDataBindingConfig()
        dataBindingConfig?.let {
            //获取ViewDataBinding
            val binding: ViewDataBinding = DataBindingUtil.setContentView(this, it.layout)
            //将ViewDataBinding生命周期与Fragment绑定
            binding.lifecycleOwner = this
            dataBindingConfig?.apply {
                val bindingParams = bindingParams
                //TODO 将bindingParams逐个加入到ViewDataBinding中的Variable
                // 这一步很重要,否则xml中拿不到variable中内容
                for (i in 0 until bindingParams.size()) {
                    binding.setVariable(bindingParams.keyAt(i), bindingParams.valueAt(i))
                }
            }
            mBinding = binding

            observe()
            init(savedInstanceState)
        }
    }

    /**
     * 获取dataBinding配置项
     */
    abstract fun getDataBindingConfig(): DataBindingConfig?

    /**
     * 设置状态栏
     * 在activity中默认为空实现，交由fragment去处理。
     * 当这个activity是没有fragment的情况下，可以进行重写设置。
     * ImmersionBar.with(this).init()
     */
    open fun setStatusBar() {

    }


    /**
     * 初始化viewModel
     * 之所以没有设计为抽象，是因为部分简单activity可能不需要viewModel
     * observe同理
     */
    open fun initViewModel() {
    }

    /**
     * 注册观察者
     */
    open fun observe() {

    }

    /**
     * 通过activity获取viewModel，跟随activity生命周期
     */
    protected fun <T : ViewModel?> getActivityViewModel(modelClass: Class<T>): T? {
        if (mActivityProvider == null) {
            mActivityProvider = ViewModelProvider(this)
        }
        return mActivityProvider?.get(modelClass)
    }

    /**
     * activity入口
     */
    abstract fun init(savedInstanceState: Bundle?)

    /**
     * 获取layout布局
     */
    abstract fun getLayoutId(): Int?
}